<?php
namespace Seller\Controller;
use Think\AjaxPage;
use Seller\Logic\GoodsLogic;

class PromotionController extends BaseController {
	
	public $store_id;
	public function __construct(){
		parent::__construct();
		$this->store_id = STORE_ID;
	}
	
    public function index(){
        $this->display();
    }
	public function tuiguang(){
	    $this->display();
	}
	
	public function full_reduction(){
	    $time = date('Y-m',time());
	    $info = M('store')->where(['store_id'=>STORE_ID])->find();
	    $info['full'] = json_decode($info['full'],true);
	    $this->assign('time',$time);
	    $this->assign('info',$info);
	    $this->display();
	}
	public function fullSave(){
	    if(IS_POST){
	        $param = I('post.');
    	    $Data = [];
    	    foreach ($param['full_price'] as $k=>$v){
    	        $Data[$k]['price'] = $v;
    	        $Data[$k]['gift'] = $param['full_gift'][$k];
    	    }
    	    $save['full'] = json_encode($Data);
    	    $save['full_shijian1'] = $param['full_shijian1'];
    	    $save['full_shijian2'] = $param['full_shijian2'];
    	    $sql = M('store')->where(['store_id'=>STORE_ID])->save($save);
    	    $this->success('修改成功');
    	    die;
	    }
	   
	}
	        /*
    * 搜索品牌分類
    */  
    
    public function search_brand(){
        
        $where = 'store_id = '.STORE_ID;
        // $where = 'level = 1';
    	if(!empty(I('keywords')))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where .= " and goods_name like '%".I('keywords')."%'" ;
    	}
    
    // 	$count = M('brand b')->field('b.id,b.name,c.name as cat_name')->join('ty_goods_category c on c.id = b.cat_id1','left')->where($where)->count();
    // 	$count = M('store_goods_class b')->field('b.cat_id,b.cat_name')->where($where)->count();
    	$count = M('goods')->where($where)->count();
    
    	$Page  = new \Think\Page($count,20);
    	$goodsList = M('goods')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
    	$show = $Page->show();//分页显示输出
    // 	dump($show);
    	$this->assign('page',$show);//赋值分页输出
    	$this->assign('goodsList',$goodsList);
    	$this->display();
    }
	//活动报名列表
	public function join_goods_list()
	{
		$keywords=I('keywords');
		$parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折');
		$level = M('user_level')->select();
		if($level){
			foreach ($level as $v){
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		$this->assign("parse_type",$parse_type);
		
		$where='a.store_id='.STORE_ID;
        
		if($keywords)
		$where=' and (a.content like "%'.$keywords.'%" or b.store_name like "%'.$keywords.'%")';
		
		$count = M('goods_join a')->field('a.*,b.store_name')->join('ty_store b on a.store_id=b.store_id','LEFT')->where($where)->count();
		$Page  = new \Think\Page($count,10);
		$show = $Page->show(); 
		$res = M('goods_join a')->field('a.*,b.store_name')->join('ty_store b on a.store_id=b.store_id','LEFT')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select(); 
		
		if($res){
			foreach ($res as $key=>$val){
				$res[$key]['state'] = empty($val['status']) ? '<span style="color:red">待审核</span>' : '<span style="color:green">已审核</span>';
				// if($val['end_time']<time()){
				// 	$res[$key]['state'] = '已结束';
				// }
			}
		}
        $this->assign('page',$show);// 赋值分页输出 
		$this->assign('prom_list',$res);
		$this->display();
	}
	
	
	/**
	 *店铺满赠活动列表
	 */
	 public function prom_full_list(){
	     $timegap = I('timegap');
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		}else{
            $begin2 = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
            $end2 = date('Y-m-d 23:59',strtotime('+1 days'));
            $begin = strtotime($begin2);
            $end = strtotime($end2);
        }
        $this->assign('timegap',$begin2.' - '.$end2);
	     $this->display();
	 }
	 
	 
    public function ajaxprom_full_list(){
	     
	    $count = M('goods_full')->where(['store_id'=>STORE_ID])->count();
	    $Page  = new AjaxPage($count,20);
        $show = $Page->show();
        $list = M('goods_full')->where(['store_id'=>STORE_ID])->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('prom_list',$list);// 赋值分页输出
	    $this->display();
	 }
	 
	 public function prom_full_info(){
	     $id = I('id');
	     $info = M('goods_full')->where(['id'=>$id,'store_id'=>STORE_ID])->find();
	     if(!empty($info['full_gift'])){
	         $info['full_gift'] = json_decode($info['full_gift'],true);
	     }
	     if(!empty($info)){
	        $info['end_time'] = date('Y-m-d H:i',$info['end_time']);
	        $info['start_time'] = date('Y-m-d H:i',$info['start_time']);
	     }
	   //  if(!empty($info['brand_id'])){
	   //      $brand_ids = implode(',',json_decode($info['brand_id'],true));
	   //  }
         if(!empty($info['goods_id'])){
	         $goods_ids = implode(',',json_decode($info['goods_id'],true));
	     }
	     if(!empty($goods_ids)){
	         $goodsList = M('goods b')->where('b.goods_id in ('.$goods_ids.')')->select();
	     }
	     
	   //  dump($goodsList);
	     $min_date = date('Y-m-d');
	     $this->assign('info',$info);
	     $this->assign('goodsList',$goodsList);
	     $this->assign('min_date',$min_date);
	     $this->display();
	 }
	 public function prom_full_save(){
	     
	     if(IS_POST){
	       
	         $param = I('');
	         $store_id = STORE_ID;
	         $sendData = [];
	         $sendData['name'] = $param['name'];
	         $sendData['type'] = $param['type'];
	         $sendData['start_time'] = strtotime($param['start_time']);
	         $sendData['end_time'] = strtotime($param['end_time']);
	            
	         if(!empty($param['goods_id'])){
                $sendData['goods_id'] = json_encode($param['goods_id']);
            }else{
                $sendData['goods_id'] = '';
            }   
	            
	         $Data = [];
    	    foreach ($param['full_price'] as $k=>$v){
    	        $Data[$k]['price'] = $v;
    	        $Data[$k]['gift'] = $param['full_gift'][$k];
    	    }
    	    if(empty($Data)){
    	        $this->success('送礼不能为空');
                die;
    	    }
    	    $sendData['full_gift'] = json_encode($Data);
    	    if($sendData['end_time'] < $sendData['start_time']){
    	        $this->success('结束时间不能小于开始时间');
                die;
    	    }
    	    //检测区间是否存在其他活动
    	   // $info = M('goods_full')->where("store_id = $store_id and start_time >= $start and end_time <=$end")->find();
    	   //  dump($sendData);
    	   //  die;
	         if(!empty($param['id'])){//修改
	            $info = M('goods_full')->where("store_id = $store_id and id=".$param['id'])->find();
	            if($info['end_time'] < time()){
	                 $this->success('已经结束，无法修改');
	                 die;
	            }
	            $info = M('goods_full')->where(['id'=>$param['id'],'store_id'=>$store_id])->save($sendData);
	            $this->success('操作成功',U('Promotion/prom_full_info',['id'=>$param['id']]));
	         }else{//新增
	            $sendData['add_time'] = time();
	            $sendData['store_id'] = $store_id;
	            $model = D('goods_full');
	            $info = $model->add($sendData);
	          
	            $this->success('操作成功',U('Promotion/prom_full_info',['id'=>$info]));
	         }
	         
	     }
	 }
	
	public function daochufull(){
	    $id = I('id');
	    $store_id = STORE_ID;
	    $info = M('goods_full')->where("store_id = $store_id and id=".$id)->find();
	    $full = json_decode($info['full_gift'],true);
	    usort($full, function ($a, $b) {
            return $a['price'] - $b['price'];
        });
        
        $begin = $info['start_time'];
        $end = $info['end_time'];
        
	    
	    
		$where .= " a.order_status in(0,1,2,4) and a.store_id=$store_id";
        $whereb="a.addtime>$begin and a.addtime<$end and b.is_lock=0";
		$sql = "select a.add_time,count(a.order_id) as order_num,sum(a.total_amount+yijia_heji) as amount,a.user_id,b.mobile,b.company,b.nickname,b.user_id,b.biaoshi,b.biaoshi_xian,b.company_address from __PREFIX__order as a left join __PREFIX__users as b on a.user_id = b.user_id where a.add_time>$begin and a.add_time<$end and $where group by a.user_id order by amount DESC";
    	$orderList = D()->query($sql);
     
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">用户ID</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="100">排行</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">礼物</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户地址</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">购物金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际金额</td>';
    	$strTable .= '</tr>';
    	foreach($orderList as $k=>$val){
    	    if($info['type'] == 1){
                $begin = strtotime(date('Y-m-d 00:00:00',$val['add_time']));
                $end = strtotime(date('Y-m-d 23:59:59',$val['add_time']));
            }
    	    //把禁止活动的剔除出去
    	    $pgoods = M('order_goods g')
    	    ->join('ty_order o on o.order_id = g.order_id','left')
    	   // ->where(['full_status'=>1,'user_id'=>$val['user_id'],'store_id'=>$store_id])
    	    ->where("g.full_status = 0 and o.order_status in (0,1,2) and o.user_id = ".$val['user_id']." and o.store_id=$store_id and o.add_time>$begin and o.add_time<$end")
    	    ->sum('(member_goods_price+yijia)*goods_num');
    	      if(empty($pgoods)){
    	          $pgoods = 0;
    	      }
    	    
    	    
           
            $userInfo = M('users')->where(['user_id'=>$val['user_id']])->find();
            $return_goods_price = 0;
            if(!empty($userInfo)){
                $tuikuan2=M('return_goods a')
                ->field("a.member_goods_price,a.goods_num")
                ->join('ty_users b on a.user_id=b.user_id')
                ->where($whereb.' and a.user_id = '.$val['user_id'])
                ->select();
              
                if(count($tuikuan2) > 0){
                    foreach ($tuikuan2 as $key => $value){
                        $return_goods_price += ($value['member_goods_price']*$value['goods_num']);
                    }
                }
            }
            
                
           $val['return_goods_price'] = $return_goods_price;
           $shiji = geshi($pgoods-$val['return_goods_price']);
           $orderList[$k]['gift'] = '';
            foreach($full as $key=>$v){
                if($shiji > $v['price']){
                    $val['gift'] = $v['gift'];
                }
            }
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['user_id'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.($k+1).' </td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['gift'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].'（'.$val['company'].'）'.' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['biaoshi_xian'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company_address'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_num'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$pgoods.'</td>';
    // 		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['amount'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['return_goods_price'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$shiji.'</td>';
    		$strTable .= '</tr>';
    	}
    
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'order');
    	exit();
	}
	
	
	public function join_goods_info()
	{
		$this->assign('min_date',date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d',time()+3600*60*24);
		if($prom_id>0){
			$info = M('goods_join')->where("id=$prom_id and store_id=".STORE_ID)->find();
			if(empty($info))
				$this->error('非法操作！');
				
			$info['start_time'] = date('Y-m-d',$info['start_time']);
			$info['end_time'] = date('Y-m-d',$info['end_time']);
			if($info['goods_key']){
				$goods_key=\json_decode($info['goods_key']);
				foreach($goods_key as $key=>$v){
					$prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
					$prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
				}
				 
			}else{
				$prom_goods = M('goods')->where("prom_id=$prom_id and store_id=".STORE_ID)->select();
			}
	
			$this->assign('prom_goods',$prom_goods);
		}
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}
	
	public function join_goods_save()
	{
		$prom_id = I('id'); 
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['goods_key'] = \json_encode($data['goods_key']);
		if($data['prom_type']==4){
			$data['zd']=1;
		}

		if($prom_id){
			M('goods_join')->where("id=$prom_id and store_id =".STORE_ID)->save($data);
			$last_id = $prom_id;
			sellerLog("管理员修改了商品促销 ".I('name'));
		}else{
			$data['store_id'] = $this->store_id;
			$last_id = M('goods_join')->add($data);
			sellerLog("管理员添加了商品促销 ".I('name'));
		}
		cart_price();
		$this->success('编辑促销活动成功',U('Promotion/join_goods_list'));
	}
	
	public function join_goods_del()
	{
		$prom_id = I('id');
	            $order_goods = M('goods_join')->where("id = $prom_id")->find();
	            if($order_good['status']==1)
	            {
	                $this->error("该活动已经审核，不能删除!请联系平台客服。");
	            }
		M('goods_join')->where("id=$prom_id")->delete();
		$this->success('删除活动成功',U('Promotion/prom_goods_list'));
	}
	
	public function join_get_goods(){
		$prom_id = I('id');
		$goods_join=M('goods_join')->where('id='.$prom_id)->find();
		$parse_type = array('0'=>'单品秒杀 %','1'=>'降价促销 元','2'=>'一口价促销 元','3'=>'买就赠优惠券','4'=>'全店打折 %');
		$this->assign("parse_type",$parse_type);
		
		if($goods_join['zd']){
			$count =M('goods')->where("store_id=".STORE_ID)->count(); 
			$goodsList = M('goods')->where("store_id=".STORE_ID)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
			foreach($goodsList as $key=>$v){
				$goodsList[$key]['key_name']='全规格';
				$goodsList[$key]['price']=$v['shop_price'];
				$goodsList[$key]['xiangou']=$goods_join['xiangou'];
				$goodsList[$key]['expression']=$goods_join['expression'];
				$goodsList[$key]['prom_type']=$goods_join['prom_type'];
			}
		}else{
			$goods_key=\json_decode($goods_join['goods_key']);
			foreach($goods_key as $key=>$v){
				$goodsList[$key]= M('spec_goods_price a')->field('a.*,b.goods_name')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
				$goodsList[$key]['xiangou']=$goods_join['xiangou'];
				$goodsList[$key]['expression']=$goods_join['expression'];
				$goodsList[$key]['prom_type']=$goods_join['prom_type'];
			}
		}
		$Page  = new \Think\Page($count,10);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->assign('goodsList',$goodsList);
		$this->display(); 
	}
	
    /**
     * 商品活动列表 
     */
	public function prom_goods_list()
    {
        $parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'买M送N');
        $level = M('user_level')->select();

        $where = [];//z
        $where['a.store_id'] = STORE_ID;
        $type = I('type');
        if($type || $type === '0'){
            $where['a.type'] = $type;
            $whereStr = " and a.type=".$where['a.type'];
        }//z
        if($level){
            foreach ($level as $v){
                $lv[$v['level_id']] = $v['level_name'];
            }
        }

        $countModel = M('prom_goods a')//===========
        ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id', 'LEFT')
            ->where("a.pgoods_id is NULL and a.miao_status =0 and a.store_id=".$this->store_id . $whereStr);

        $count = $countModel->count();//---------

// ✅ 打印 count 查询的 SQL
//        echo "<pre>【Count SQL】：" . $countModel->getLastSql() . "</pre>";

        $Page  = new \Think\Page($count,10);
        $show = $Page->show();
        $resModel = M('prom_goods a')//========
        ->field('a.*,b.store_name,b.zhekou')
            ->join('ty_store b on a.store_id=b.store_id', 'LEFT')
            ->where("a.pgoods_id is NULL and a.miao_status =0 and a.store_id=".$this->store_id . $whereStr)
            ->order('a.id desc')
            ->limit($Page->firstRow.','.$Page->listRows);

        $res = $resModel->select();//---------
        // 打印 count 查询的 SQL
//        echo "<pre>【Select SQL】：" . $resModel->getLastSql() . "</pre>";

        //       $count = M('prom_goods')->where("store_id=".$this->store_id)->count();
        //       $Page  = new \Think\Page($count,10);
        //       $show = $Page->show();
        // $res = M('prom_goods')->where("store_id=".$this->store_id)->limit($Page->firstRow.','.$Page->listRows)->select();
        if($res){
            foreach ($res as $val){
                if(!empty($val['group']) && !empty($lv)){
                    $val['group'] = explode(',', $val['group']);
                    foreach ($val['group'] as $v){
                        $val['group_name'] .= $lv[$v].',';
                    }
                }
                $val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
                if($val['end_time']<time()){
                    $val['state'] = '已结束';
                }
                $prom_list[] = $val;
            }
        }
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('prom_list',$prom_list);
        $this->assign('parse_type', $parse_type);
        $this->display();
    }
	
	public function prom_goods_info()
	{
		$this->assign('min_date',date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
        $starTime = strtotime($info['start_time']);

        $info['start_time'] = date('Y-m-d H:i',$starTime);
		$info['end_time'] = date('Y-m-d H:i',$starTime+86399);
		if($prom_id>0){
			$info = M('prom_goods')->where("id=$prom_id and store_id=".STORE_ID)->find();
			if(empty($info))
				$this->error('非法操作！');
				
			$info['start_time'] = date('Y-m-d H:i',$info['start_time']);
			$info['end_time'] = date('Y-m-d H:i',$info['end_time']);
			if($info['goods_key']){
				$goods_key=\json_decode($info['goods_key']);
				foreach($goods_key as $key=>$v){
					$prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
					$prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
				}
				 
			}else{
				$prom_goods = M('goods')->where("prom_id=$prom_id and store_id=".STORE_ID)->select();
			}

			$this->assign('prom_goods',$prom_goods);
		}
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}
	
	public function prom_goods_save()
	{
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['group'] = implode(',', $data['group']);
        $data['prom_code'] = $data['prom_code'];
		$data['goods_key'] = \json_encode($data['goods_key']);

		if($prom_id){
			M('prom_goods')->where("id=$prom_id and store_id =".STORE_ID)->save($data);
			$last_id = $prom_id;
			sellerLog("管理员修改了商品促销 ".I('name'));
		}else{
			$data['store_id'] = $this->store_id;
			$last_id = M('prom_goods')->add($data);
			sellerLog("管理员添加了商品促销 ".I('name'));
		}
		
		if(is_array($data['goods_id'])){
			$goods_id = implode(',',array_unique($data['goods_id']));
			if($prom_id>0){
				M("goods")->where("prom_id=$prom_id and prom_type=".$data["type"]." and store_id =".STORE_ID)->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
			}
			M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
		}
		cart_price();
		$this->success('编辑促销活动成功',U('Promotion/prom_goods_list'));
	}
	
	public function prom_goods_del()
	{
		$prom_id = I('id');
		$prom_goods = M('prom_goods')->where("id = $prom_id")->find();
		if($prom_goods['zd']==1){
			$this->error("全店折扣活动不能删除!");
		}
        if($prom_goods['end_time']>time())
        {
            $this->error("该活动时间未结束不能删除!");    
        }
		M("goods")->where("prom_id=$prom_id and store_id = {$this->store_id}")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
		M('prom_goods')->where("id=$prom_id and store_id = {$this->store_id}")->delete();
		$this->success('删除活动成功',U('Promotion/prom_goods_list'));
	}

    /**
     * 每日秒杀
     * */
    public function daily_goods_list(){

        $parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价秒杀','3'=>'买就赠优惠券','4'=>'全店打折',5=>'折扣秒杀');
        $level = M('user_level')->select();
        if($level){
            foreach ($level as $v){
                $lv[$v['level_id']] = $v['level_name'];
            }
        }
        $this->assign("parse_type",$parse_type);

        $count = M('prom_goods a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where('a.miao_status = 1 and a.store_id = '.$this->store_id)
            ->count();
        $Page  = new \Think\Page($count,10);
        $show = $Page->show();
        $res = M('prom_goods a')
            ->field('a.*,b.store_name,b.zhekou')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where('a.miao_status = 1 and a.store_id = '.$this->store_id)
            ->order('a.id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        if($res){
            foreach ($res as $val){
                if(!empty($val['group']) && !empty($lv)){
                    $val['group'] = explode(',', $val['group']);
                    foreach ($val['group'] as $v){
                        $val['group_name'] .= $lv[$v].',';
                    }
                }
                // $val['state'] = empty($val['status']) ? '审核不通过' : '正常';
                if($val['status'] == 0){
                    $val['state'] = '审核中';
                }
                if($val['status'] == 1){
                    $val['state'] = '正常';
                }
                if($val['status'] == 2){
                    $val['state'] = '审核不通过';
                }
                if($val['end_time']<time()){
                    $val['state'] = '已结束';
                }
                $prom_list[] = $val;
            }
        }
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('prom_list',$prom_list);
        $this->display();
    }
    public function daily_goods_info()
    {
        // $this->assign('min_date',date('Y-m-01'));
        $level = M('user_level')->select();
        $this->assign('level',$level);
        $prom_id = I('id');
        $info['start_time'] = date('Y-m-d');
        $info['end_time'] = date('Y-m-d',time()+3600*60*24);
        if($prom_id>0){
            $info = M('prom_goods')->where("id=$prom_id and store_id=".STORE_ID)->find();
            if(empty($info))
                $this->error('非法操作！');

            $info['start_time'] = date('Y-m-d',$info['start_time']);
            $info['end_time'] = date('Y-m-d',$info['end_time']);
            if($info['goods_key']){
                $goods_key=\json_decode($info['goods_key']);
                foreach($goods_key as $key=>$v){
                    $prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
                    $prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
                }

            }else{
                $prom_goods = M('goods')->where("prom_id=$prom_id and store_id=".STORE_ID)->select();
            }

            $this->assign('prom_goods',$prom_goods);
            $this->assign('min_date',date('Y-m-d',$info['start_time']));
        }else{
            $this->assign('min_date',date('Y-m-01'));
        }
        
        $this->assign('info',$info);
        
        $this->initEditor();
        $this->display();
    }


    public function daily_goods_save()
    {
        $prom_id = I('id');
        $data = I('post.');
      
//        $data['start_time'] = strtotime($data['start_time']);
//        $data['end_time'] = strtotime($data['end_time']);

        $time = $data['times'];
        $data['start_time'] = strtotime($time);
        $data['end_time'] = $data['start_time']+86399;
        $data['group'] = implode(',', $data['group']);
        $data['prom_code'] = $data['prom_code'];
        $data['miao_status'] = 1;
        //只允许三件商品
        $length = 0;
        if(!empty($data['goods_id'])){
            $goodsID = array_unique($data['goods_id']);
            $length = count($goodsID,COUNT_NORMAL);
            if($length>3){
                $this->error('每日秒杀只能选择三个个商品多个规格');
            }
        }
        $data['goods_key'] = \json_encode($data['goods_key']);
         //查询商家是否有这一天秒杀
        
        if($prom_id){
            $promData = M('prom_goods')->where(['id'=>$prom_id])->find();//获取要修改的活动
            
            //  $prom = M('prom_goods')->where('start_time = '.$data['start_time'].' and end_time = '.$data['end_time'])->where(['miao'=>5,'store_id'=>$this->store_id])->find();
             $prom = M('prom_goods')->where("id=$prom_id and store_id=".$this->store_id)->find();
             
            //找到同一天有数据可以修改商品不可以修改为同一天日期
             if(!empty($prom)){
                 //如果已经存在这个日期的每日秒杀，
                 if($prom['id'] != $prom_id){
                     if($data['start_time'] == $prom['start_time']){
                          $this->error('不可编辑多条同一天');
                     }
                 }
                if($data['end_time'] < time()){
                      $this->error('时间已过，无法修改');
                 }
             }
            // if($count){
            //     $this->error('当天已经有秒杀');
            // }
            $data['status'] = 0;
            M('prom_goods')->where("id=$prom_id and store_id =".STORE_ID)->save($data);
            $last_id = $prom_id;
            sellerLog("修改了每日秒杀 ".I('name'));
        }else{
            $data['store_id'] = $this->store_id;
            $prom = M('prom_goods')->where('start_time = '.$data['start_time'].' and end_time = '.$data['end_time'])->where(['type'=>5,'store_id'=>$this->store_id])->find();
            if(!empty($prom)){
                $this->error('当天已经有秒杀');
            }
            $data['status'] = 0;
        
            $last_id = M('prom_goods')->add($data);
            sellerLog("添加了每日秒杀 ".I('name'));
        }
        //总后台审核添加数据，这里不做修改
        if(is_array($data['goods_id'])){
            $goods_id = implode(',',array_unique($data['goods_id']));
            if($prom_id>0){
                M("goods")->where("prom_id=$prom_id and prom_type=".$data["type"]." and store_id =".STORE_ID)->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
            }
            M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
            if($data['expression']=='100'){
                M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
            }else{
                M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
            }
        }
        // cart_price();
        $this->success('编辑每日秒杀成功',U('Promotion/daily_goods_list'));
    }

    public function daily_goods_del()
    {
        $prom_id = I('id');
        $prom_goods = M('prom_goods')->where("id = $prom_id")->find();
        // if($prom_goods['end_time']>time())
        // {
        //     $this->error("该活动时间未结束不能删除!");
        // }
        M("goods")->where("prom_id=$prom_id and store_id = {$this->store_id}")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
        M('prom_goods')->where("id=$prom_id and store_id = {$this->store_id}")->delete();
        
       $return_arr = array(
            'code' => 1,
            'msg'   => '删除每日秒杀成功',
            'data'  => [],
        );
        $this->ajaxReturn($return_arr);
        $this->success('删除每日秒杀成功',U('Promotion/daily_goods_list'));
    }
        /**
         * 订单活动列表
         */
	public function prom_order_list()
	{
		$parse_type = array('0'=>'满额打折','1'=>'满额优惠金额','2'=>'满额送积分','3'=>'满额送优惠券');
        $count = M('prom_order')->where("store_id=".$this->store_id)->count();
        $Page  = new \Think\Page($count,10);    	 
        $show = $Page->show();               
		$res = M('prom_order')->where("store_id=".$this->store_id)->limit($Page->firstRow.','.$Page->listRows)->select();
		$level = M('user_level')->select();
		if($level){
			foreach ($level as $v){
				$lv[$v['level_id']] = $v['level_name'];
			}
		}
		if($res){
			foreach ($res as $val){
				if(!empty($val['group']) && !empty($lv)){
					$val['group'] = explode(',', $val['group']);
					foreach ($val['group'] as $v){
						$val['group_name'] .= $lv[$v].',';
					}
				}
				$val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
				if($val['end_time']<time()){
					$val['state'] = '已结束';
				}
				$prom_list[] = $val;
			}
		}
        $this->assign('page',$show);// 赋值分页输出
        $this->assign("parse_type",$parse_type);
		$this->assign('prom_list',$prom_list);
		$this->display();
	}
	
	public function prom_order_info(){
		$this->assign('min_date',date('Y-m-d'));
		$level = M('user_level')->select();
		$this->assign('level',$level);
		$prom_id = I('id');
		$info['start_time'] = date('Y-m-d');
		$info['end_time'] = date('Y-m-d',time()+3600*24*60);
		if($prom_id>0){
			$info = M('prom_order')->where("id=$prom_id")->find();
			$info['start_time'] = date('Y-m-d',$info['start_time']);
			$info['end_time'] = date('Y-m-d',$info['end_time']);
		}
		$this->assign('info',$info);
		$this->assign('min_date',date('Y-m-d'));
		$this->initEditor();
		$this->display();
	}
	
	public function prom_order_save(){
		$prom_id = I('id');
		$data = I('post.');
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		$data['group'] = implode(',', $data['group']);
		if($prom_id){
			M('prom_order')->where("id=$prom_id and store_id = {$this->store_id}")->save($data);
			sellerLog("管理员修改了商品促销 ".I('name'));
		}else{
			$data['store_id'] = $this->store_id;
			M('prom_order')->add($data);
			sellerLog("管理员添加了商品促销 ".I('name'));
		}
		$this->success('编辑促销活动成功',U('Promotion/prom_order_list'));
	}
	
	public function prom_order_del()
	{
		$prom_id = I('id');                                
                $order = M('order')->where("order_prom_id = $prom_id and store_id = {$this->store_id}")->find();
                if(!empty($order))
                {
                    $this->error("该活动有订单参与不能删除!");    
                }
                                
		M('prom_order')->where("id=$prom_id  and store_id = {$this->store_id}")->delete();
		$this->success('删除活动成功',U('Promotion/prom_order_list'));
	}
	
    public function group_buy_list(){
    	$Ad =  M('group_buy');
    	$p = I('p',1);
        
    	$count = $Ad->where("store_id=".$this->store_id)->count();
    	$Page = new \Think\Page($count,10);        
    	$res = $Ad->order('id desc')->where("store_id=".$this->store_id)->limit($Page->firstRow.','.$Page->listRows)->select();
    	if($res){
    		foreach ($res as $val){
    			$val['start_time'] = date('Y-m-d H:i',$val['start_time']);
    			$val['end_time'] = date('Y-m-d H:i',$val['end_time']);
    			$list[] = $val;
    		}
    	}
    	$this->assign('list',$list);
    	$this->assign('state',array('审核中','正常','未通过','管理员关闭'));
    	$show = $Page->show();
    	$this->assign('page',$show);
    	$this->display();
    }
    
    //团购促销
    public function group_buy(){
    	$act = I('GET.act','add');
    	$groupbuy_id = I('get.id');
    	$group_info = array();
    	$group_info['start_time'] = date('Y-m-d');
    	$group_info['end_time'] = date('Y-m-d',time()+3600*365);
    	if($groupbuy_id){
    		$group_info = D('group_buy')->where('id='.$groupbuy_id)->find();
    		$group_info['start_time'] = date('Y-m-d H:i',$group_info['start_time']);
    		$group_info['end_time'] = date('Y-m-d H:i',$group_info['end_time']);
    		$act = 'edit';
    	}
    	$this->assign('min_date',date('Y-m-d'));
    	$this->assign('info',$group_info);
    	$this->assign('act',$act);
    	$this->display();
    }
    
    public function groupbuyHandle(){
    	$data = I('post.');
    	$data['groupbuy_intro'] = htmlspecialchars(stripslashes($_POST['groupbuy_intro']));
    	$data['start_time'] = strtotime($data['start_time']);
    	$data['end_time'] = strtotime($data['end_time']);
		$rebate=$data['price']/$data['goods_price'];
		$data['rebate'] =$rebate*10;
    	if($data['act'] == 'del'){
            $r = D('group_buy')->where("id= {$data['id']} and store_id = {$this->store_id}")->delete();
    		M('goods')->where("prom_type=2 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
    		if($r) exit(json_encode(1));
    	}
    	if($data['act'] == 'add'){
    		$data['store_id'] = $this->store_id;
    		$r = D('group_buy')->add($data);
    		M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$r,'prom_type'=>2));
    	}
    	if($data['act'] == 'edit'){
            $r = D('group_buy')->where("id = {$data['id']}  and store_id = {$this->store_id}")->save($data);
    		M('goods')->where("prom_type=2 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
    		M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$data['id'],'prom_type'=>2));
    	}
    	if($r){
    		$this->success("操作成功",U('Promotion/group_buy_list'));
    	}else{
    		$this->error("操作失败",U('Promotion/group_buy_list'));
    	}
    }
    
    public function get_goods(){
    	$prom_id = I('id');
		if(I('action')=='quxiao'){
			$goods_id=I('goods_id');
			M('goods')->where("goods_id=$goods_id and store_id=".$this->store_id)->setField(['prom_type'=>0,'prom_id'=>0,'zd'=>0]);
			exit;
		}
		//$proms=M('prom_goods')->where('id='.$prom_id)->find();
		!empty(I('keywords')) ? $where=" and goods_name like '%".I('keywords')."%'" : $where=""; 
    	$count = M('goods')->where("prom_id=$prom_id and store_id=".$this->store_id.$where)->count();
    	$Page  = new \Think\Page($count,10);
    	$goodsList = M('goods')->where("prom_id=$prom_id and store_id=".$this->store_id.$where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$show = $Page->show();
    	$this->assign('page',$show);
    	$this->assign('goodsList',$goodsList);
    	$this->display(); 
    }   
    
    public function search_goods(){
    	$GoodsLogic = new \Admin\Logic\GoodsLogic;
    	$brandList = $GoodsLogic->getSortBrands();
    	$this->assign('brandList',$brandList);
    	$categoryList = $GoodsLogic->getSortCategory();
    	$this->assign('categoryList',$categoryList);
    	
        /*
         * 可以用这两条sql 语句代替 
         * select group_concat(concat( class_1,',',class_2,',',class_3 )) from tp_store_bind_class group by store_id
         * select group_concat(concat_ws( ',',class_1,class_2,class_3 )) from tp_store_bind_class group by store_id         
         */
        $bind_class_id = array();
        $store_bind_class = M('store_bind_class')->where("store_id = ".STORE_ID." and state = 1")->select();
        foreach($store_bind_class as $key => $val)
        {
            $bind_class_id[] = $val['class_1']; 
            $bind_class_id[] = $val['class_2']; 
            $bind_class_id[] = $val['class_3']; 
        }
        $this->assign('bind_class_id',$bind_class_id);
        
    	$goods_id = I('goods_id');
    	$where = 'prom_lock=0 and b.is_on_sale = 1 and b.store_id='.$this->store_id;//搜索条件and b.prom_type=0 
    	// if(!empty($goods_id)){
    	// 	$where .= " and a.goods_id not in ($goods_id) ";
    	// }
    	I('intro')  && $where = "$where and ".I('intro')." = 1";
        $cat_id = I('cat_id');
    	if($cat_id){
    		$this->assign('cat_id',$cat_id);
    		$goods_category = M('goods_category')->where("id = $cat_id")->find();
    		$where = " $where  and cat_id{$goods_category['level']} = $cat_id"; // 初始化搜索条件
    	}
    	if(I('brand_id')){
    		$this->assign('brand_id',I('brand_id'));
    		$where = "$where and brand_id = ".I('brand_id');
    	}
    	if(!empty($_REQUEST['keywords']))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "$where and (b.goods_name like '%".I('keywords')."%' or b.goods_id like '%".I('keywords')."%' or b.keywords like '%".I('keywords')."%')" ;
    	}
    	$count = M('spec_goods_price a')->field('a.key,a.key_name,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where($where)->count();
    	$Page  = new \Think\Page($count,30);
		
    	$goodsList = M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where($where)->order('goods_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$show = $Page->show();//分页显示输出
    	$this->assign('page',$show);//赋值分页输出
    	$this->assign('goodsList',$goodsList);
    	$tpl = I('get.tpl','search_goods');
    	$this->display($tpl);
    }
    
    //限时抢购
    public function flash_sale(){
    	$model = M('flash_sale');
    	$count = $model->where("store_id=".$this->store_id)->count();
    	$Page  = new \Think\Page($count,10);    	 
    	$show = $Page->show();
    	$prom_list = $model->where("store_id=".$this->store_id)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('state',array('审核中','正常','未通过','管理员关闭'));
    	$this->assign('prom_list',$prom_list);
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display();
    }
    
    public function flash_sale_info(){
    	if(IS_POST){
    		$data = I('post.');
    		$data['start_time'] = strtotime($data['start_time']);
    		$data['end_time'] = strtotime($data['end_time']);
    		if(empty($data['id'])){
    			$data['store_id'] = $this->store_id;
    			$r = M('flash_sale')->add($data);
    			M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$r,'prom_type'=>1));
    			sellerLog("管理员添加抢购活动 ".$data['name']);
    		}else{
    			$r = M('flash_sale')->where("id = {$data['id']} and store_id = {$this->store_id}")->save($data);
    			M('goods')->where("prom_type=1 and prom_id=".$data['id'])->save(array('prom_id'=>0,'prom_type'=>0));
    			M('goods')->where("goods_id=".$data['goods_id'])->save(array('prom_id'=>$data['id'],'prom_type'=>1));
    		}
    		if($r){
    			$this->success('编辑抢购活动成功',U('Promotion/flash_sale'));
    			exit;
    		}else{
    			$this->error('编辑抢购活动失败',U('Promotion/flash_sale'));
    		}
    	}
    	$id = I('id');
    	$info['start_time'] = date('Y-m-d H:i:s');
    	$info['end_time'] = date('Y-m-d 23:59:59',time()+3600*24*60);
    	if($id>0){
    		$info = M('flash_sale')->where("id=$id")->find();
    		$info['start_time'] = date('Y-m-d H:i',$info['start_time']);
    		$info['end_time'] = date('Y-m-d H:i',$info['end_time']);
    	}
    	$this->assign('info',$info);
    	$this->assign('min_date',date('Y-m-d'));
    	$this->display();
    }
    
    public function flash_sale_del(){
    	$id = I('del_id');
    	if($id){
    		M('flash_sale')->where("id = $id  and store_id = {$this->store_id}")->delete();
    		M('goods')->where("prom_type=1 and prom_id=$id")->save(array('prom_id'=>0,'prom_type'=>0));
    		 exit(json_encode(1));
    	}else{
    		 exit(json_encode(0));
    	}
    }
    
    private function initEditor()
    {
    	$this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'promotion')));
    	$this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'promotion')));
    	$this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'promotion')));
    	$this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'promotion')));
    	$this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'promotion')));
    	$this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'promotion')));
    	$this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'promotion')));
    	$this->assign("URL_Home", "");
    }
    
}